package cn.zh.sql_session.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = MasterDataSourceConfig.MAPPER_PACKAGE,sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {

    static final String MAPPER_LOCATION = "classpath:master/*.xml";
    static final String MAPPER_PACKAGE = "cn.zh.sql_session.mapper.master";
    static final String DOMAIN_PACKAGE = "cn.zh.sql_session.domain.entity.master";

    @Bean("masterDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource(){
        // return new DruidDataSource();
        return DataSourceBuilder.create()
                .type(DruidDataSource.class).build();
    }

    @Bean("masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {

        // Mybatis 需要使用 SqlSessionFactoryBean
//        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();

        // Mybatis-Plus 需要使用 MybatisSqlSessionFactoryBean
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactory.setDataSource(dataSource);
        // 设置扫描别名路径（Mybatis实体类别名路径）
        sqlSessionFactory.setTypeAliasesPackage(DOMAIN_PACKAGE);
        // 设置xml路径
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sqlSessionFactory.getObject();
    }

    @Bean("masterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("masterTransactionManager")
    @Primary
    public PlatformTransactionManager platformTransactionManager(){
        return new DataSourceTransactionManager(masterDataSource());
    }
}
